package com.hjj.springboot.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hjj.springboot.config.LogType;
import com.hjj.springboot.config.SystemLogs;
import com.hjj.springboot.entity.*;
import com.hjj.springboot.service.*;
import com.hjj.springboot.util.DateUtil;
import com.hjj.springboot.util.StringUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/product")
public class AdminProductController {
    
    @Autowired
    private IProductService productService;

    @Autowired
    private ICommentService commentService;

    @Autowired
    private IOrderTipsService orderTipsService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IOrderDetailService orderDetailService;

    @Value("${productImagesFilePath}")
    private String productImagesFilePath;

    @Value("${swiperImagesFilePath}")
    private String swiperImagesFilePath;

    @Value("${productIntroImagesFilePath}")
    private String productIntroImagesFilePath;

    @RequestMapping("/list")
    public R list(@RequestBody PageBean pageBean) {
        Map<String, Object> map = new HashMap<>();
        map.put("name",pageBean.getQuery().trim());
        map.put("start",pageBean.getStart());
        map.put("pageSize",pageBean.getPageSize());
        List<Product> productList=productService.list(map);
        Long total=productService.getTotal(map);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("productList",productList);
        resultMap.put("total",total);
        return R.ok(resultMap);
    }

    //更新热门状态
    @SystemLogs(operation = "商品热门状态",type = LogType.UPDATE)
    @GetMapping("/updateHot/{id}/state/{hot}")
    public R updateHot(@PathVariable(value = "id")Integer id,@PathVariable(value = "hot")Boolean hot) {
        Product product = productService.getById(id);
        product.setHot(hot);
        if (hot){
            product.setHotDateTime(new Date());
        }else {
            product.setHotDateTime(null);
        }
        productService.saveOrUpdate(product);
        return R.ok();
    }

    //更新首页轮播状态
    @SystemLogs(operation = "商品首页轮播状态",type = LogType.UPDATE)
    @GetMapping("/updateSwiper/{id}/state/{swiper}")
    public R updateSwiper(@PathVariable(value = "id")Integer id,@PathVariable(value = "swiper")Boolean swiper) {
        Product product = productService.getById(id);
        product.setSwiper(swiper);
        productService.saveOrUpdate(product);
        return R.ok();
    }

    @SystemLogs(operation = "商品信息",type = LogType.DELETE)
    @GetMapping("/delete/{id}")
    public R delete(@PathVariable(value = "id")Integer id) {
        Product product = productService.getById(id);
        productService.removeById(id);
        List<OrderDetail> orderDetailList=orderDetailService.list(new QueryWrapper<OrderDetail>().eq("goodsId",product.getId()));
        for (OrderDetail orderDetail:orderDetailList){
            List<Order> orderList=orderService.list(new QueryWrapper<Order>().eq("id",orderDetail.getMId()));
            for (Order order:orderList){
                orderDetailService.remove(new QueryWrapper<OrderDetail>().eq("mId",order.getId()));
                orderTipsService.remove(new QueryWrapper<OrderTips>().eq("orderNo",order.getOrderNo()));
                orderService.removeById(order.getId());
            }
        }
        commentService.remove(new QueryWrapper<Comment>().eq("gId",product.getId()));
        return R.ok();
    }

    //    批量删除
    @SystemLogs(operation = "商品信息",type = LogType.BATCH_DELETE)
    @PostMapping("/deleteBatch")
    public R deleteBatch(@RequestBody List<Integer> ids) {
        productService.removeByIds(ids);
        List<OrderDetail> orderDetailList=orderDetailService.list(new QueryWrapper<OrderDetail>().in("goodsId",ids));
        for (OrderDetail orderDetail:orderDetailList){
            List<Order> orderList=orderService.list(new QueryWrapper<Order>().eq("id",orderDetail.getMId()));
            for (Order order:orderList){
                orderDetailService.remove(new QueryWrapper<OrderDetail>().eq("mId",order.getId()));
                orderTipsService.remove(new QueryWrapper<OrderTips>().eq("orderNo",order.getOrderNo()));
                orderService.removeById(order.getId());
            }
        }
        commentService.remove(new QueryWrapper<Comment>().in("gId",ids));
        return R.ok();
    }

    @GetMapping("/export")
    public void export(@RequestParam(required = false) String query, HttpServletResponse response)   throws Exception {
        String queryStr=query.trim();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("商品信息", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<Product> productList = productService.list(new QueryWrapper<Product>().like(StringUtil.isNotEmpty(queryStr),"name",query));
        EasyExcel.write(response.getOutputStream(),Product.class)
                .sheet("商品信息")
                .doWrite(productList);
    }

    //    上传商品图片
    @SystemLogs(operation = "商品图片",type = LogType.UPLODE)
    @RequestMapping("/uploadImage")
    public Map<String,Object> uploadImage(MultipartFile file) throws Exception {
        Map<String,Object> reultMap=new HashMap<>();
        if(!file.isEmpty()){
            String originalFilename= file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName= DateUtil.getCurrentDateStr()+suffix;
            FileUtils.copyInputStreamToFile(file.getInputStream(),new File(productImagesFilePath+newFileName));
            reultMap.put("code",0);
            reultMap.put("msg","上传成功");
            Map<String,Object> dataMap=new HashMap<>();
            dataMap.put("title",newFileName);
            dataMap.put("src","img/product/"+newFileName);
            reultMap.put("data",dataMap);
        }
        return reultMap;
    }

    //    上传首页轮播图片
    @SystemLogs(operation = "首页轮播图片",type = LogType.UPLODE)
    @RequestMapping("/uploadSwiperImage")
    public Map<String,Object> uploadSwiperImage(MultipartFile file) throws Exception {
        Map<String,Object> reultMap=new HashMap<>();
        if(!file.isEmpty()){
            String originalFilename= file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName= DateUtil.getCurrentDateStr()+suffix;
            FileUtils.copyInputStreamToFile(file.getInputStream(),new File(swiperImagesFilePath+newFileName));
            reultMap.put("code",0);
            reultMap.put("msg","上传成功");
            Map<String,Object> dataMap=new HashMap<>();
            dataMap.put("title",newFileName);
            dataMap.put("src","img/swiper/"+newFileName);
            reultMap.put("data",dataMap);
        }
        return reultMap;
    }

    @SystemLogs(operation = "商品信息",type = LogType.UPDATE)
    @RequestMapping("/save")
    public R save(@RequestBody Product product) {
        System.out.println(product);
        if(product.getId()==null || product.getId()==-1){
            productService.add(product);
        }else {
            productService.update(product);
        }
        return R.ok();
    }

    @GetMapping("/{id}")
    public R findById(@PathVariable(value = "id")Integer id){
        Product product=productService.findById(id);
        Map<String,Object> map=new HashMap<>();
        map.put("product",product);
        return R.ok(map);
    }

    //    上传商品图片
    @SystemLogs(operation = "商品介绍图片",type = LogType.UPLODE)
    @RequestMapping("/uploadIntroImage")
    public Map<String,Object> uploadIntroImage(MultipartFile file) throws Exception {
        Map<String,Object> reultMap=new HashMap<>();
        if(!file.isEmpty()){
            String originalFilename= file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName= DateUtil.getCurrentDateStr()+suffix;
            FileUtils.copyInputStreamToFile(file.getInputStream(),new File(productIntroImagesFilePath+newFileName));
            reultMap.put("code",0);
            reultMap.put("msg","上传成功");
            Map<String,Object> dataMap=new HashMap<>();
            dataMap.put("title",newFileName);
            dataMap.put("src","http://localhost:8081/img/productIntroImgs/"+newFileName);
            reultMap.put("data",dataMap);
        }
        return reultMap;
    }
}
